package com.lanyou.esb.web.serviceMonitor;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.gson.GsonUtil;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.exception.IfAlarmException;
import com.lanyou.esb.redis.vo.IfAlarmVo;
import com.lanyou.esb.service.ServiceAlarmManagementService;
import com.lanyou.esb.vo.IfAvgResTimesVo;
import com.lanyou.esb.web.param.ServiceAlarmManagementParam;

/**
 * 服务告警管理控制器
 * 
 * @author Davey.wu
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/serviceAlarmManagement")
public class ServiceAlarmManagementController {
	@Autowired
	UserSessionService userSessionService;
	@Autowired
	private ServiceAlarmManagementService serviceAlarmManagementService;

	private static FastDateFormat FASTDATEFORMAT_YYYYMMDDHHMMSS = FastDateFormat
			.getInstance(Constants.DATETIME_PATTERN_1);

	/**
	 * 查找服务告警
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/findServiceAlarmManagementInfo")
	public Page<IfAlarmVo> findServiceAlarmManagementInfo(
			ServiceAlarmManagementParam param, Pageable pageable)
			throws IOException {
		User user = userSessionService.getCurrentAuthenticatedUser();

		return serviceAlarmManagementService.findServiceAlarmManagementInfo(
				user != null ? user.getId() : "", param, pageable);
	}

	@RequestMapping(value = "/saveWorkOrder", produces = "application/json")
	public String saveWorkOrder(String ifAlarmId, String errorAnalysis,
			String assignDate) {
		Map<String, Object> result = new HashMap<>(2);
		String errorMsg = "";
		// 告警信息为空，不走流程
		if (StringUtils.isBlank(ifAlarmId)) {
			errorMsg = "告警信息标识不能为空";
		}
		// 派单时间为空，不走流程
		if (StringUtils.isBlank(assignDate)) {
			errorMsg += "派单时间不能为空";
		}
		// 有错误产生，返回
		if (StringUtils.isNotBlank(errorMsg)) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, errorMsg);
			return GsonUtil.getDefaultGson().toJson(result);
		}
		Date date = null;
		try {
			date = FASTDATEFORMAT_YYYYMMDDHHMMSS.parse(assignDate);
		} catch (ParseException e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG,
					"派单日期格式不对，正确的格式为：yyyy-MM-dd HH:mm:ss");
			return GsonUtil.getDefaultGson().toJson(result);
		}

		try {
			serviceAlarmManagementService.saveWorkOrder(ifAlarmId,
					errorAnalysis, date,
					userSessionService.getCurrentAuthenticatedUser());
			result.put(CommonUtils.MSG_FIELD_RESULT, true);
		} catch (IfAlarmException e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}

		return GsonUtil.getDefaultGson().toJson(result);

	}

	/**
	 * 隔离接口
	 * 
	 * @param ifAlarmId
	 * @return
	 */
	@RequestMapping(value = "/isolation", produces = "application/json")
	public String isolation(String ifAlarmId) {
		Map<String, Object> result = new HashMap<>(2);

		// 告警信息为空，不走流程
		if (StringUtils.isBlank(ifAlarmId)) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, "告警信息标识不能为空");
			return GsonUtil.getDefaultGson().toJson(result);
		}
		try {
			serviceAlarmManagementService.isolation(ifAlarmId,
					userSessionService.getCurrentAuthenticatedUser());

			result.put(CommonUtils.MSG_FIELD_RESULT, true);
		} catch (Exception e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);

	}

	/**
	 * 取消接口隔离
	 * 
	 * @param ifAlarmId
	 * @return
	 */
	@RequestMapping(value = "/cancelIsolation", produces = "application/json")
	public String cancelIsolation(String ifAlarmId) {
		Map<String, Object> result = new HashMap<>(2);

		// 告警信息为空，不走流程
		if (StringUtils.isBlank(ifAlarmId)) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, "告警信息标识不能为空");
			return GsonUtil.getDefaultGson().toJson(result);
		}
		try {
			serviceAlarmManagementService.cancelIsolation(ifAlarmId,
					userSessionService.getCurrentAuthenticatedUser());
			result.put(CommonUtils.MSG_FIELD_RESULT, true);
		} catch (Exception e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);

	}

	/**
	 * 获取平均响应时间
	 * 
	 * @param ifId
	 *            ：接口名称
	 * @param date
	 *            ：告警时间
	 * @param peakValue
	 *            ：告警峰值
	 * @return
	 */
	@RequestMapping(value = "/findIfAvgResTiems", produces = "application/json")
	public String findIfAvgResTiems(String ifId, String date, Float peakValue) {
		Map<String, Object> result = new HashMap<>(2);
		String msg = "";
		// 告警信息为空，不走流程
		if (StringUtils.isBlank(ifId)) {
			msg = "接口标识不能为空";
		}
		// 告警信息为空，不走流程
		if (StringUtils.isBlank(date)) {
			msg = "告警时间不能为空";
		}
		// 告警信息为空，不走流程
		if (StringUtils.isNotBlank(msg)) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, msg);
			return GsonUtil.getDefaultGson().toJson(result);
		}
		Date occDate = null;
		try {
			occDate = FASTDATEFORMAT_YYYYMMDDHHMMSS.parse(date);
		} catch (ParseException e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG,
					"派单日期格式不对，正确的格式为：yyyy-MM-dd HH:mm:ss");
			return GsonUtil.getDefaultGson().toJson(result);
		}
		try {
			List<IfAvgResTimesVo> times = serviceAlarmManagementService
					.findIfAvgResTiems(ifId, occDate);
			if (times == null) {
				times = new ArrayList<>(1);
			}
			// 添加当前告警记录值
			IfAvgResTimesVo vo = new IfAvgResTimesVo();
			vo.setAvgResTimes(peakValue == null ? 0.0f : peakValue.floatValue());
			vo.setStartDate(date);
			times.add(vo);
			IfAvgResTimesVo[] array = times.toArray(new IfAvgResTimesVo[times
					.size()]);

			Arrays.sort(array, new Comparator<IfAvgResTimesVo>() {
				@Override
				public int compare(IfAvgResTimesVo o1, IfAvgResTimesVo o2) {
					return o1.getStartDate().compareToIgnoreCase(
							o2.getStartDate());
				}

			});
			times = Arrays.asList(array);
			result.put(CommonUtils.MSG_FIELD_RESULT, true);
			result.put(CommonUtils.MSG_FIELD_VALUE, times);
		} catch (IfAlarmException e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);

	}
}
